import axios from 'axios';
import VueAxios from 'vue-axios';
import { getDateTime } from './helpers';

let $app = null;
let message = null;
let key = 'axios-loading';

let install = function (app) {
  $app = app;
  message = $app._context.provides.$message;

  $app.provide('$http', axios);

  app.use(VueAxios, axios);
};

axios.interceptors.request.use(config => {
  let store = $app._context.provides.store;

  if (window.settings.apiHost) {
    config.url = `${window.settings.apiHost}${config.url}`;
  }

  if (config.resolve != false && window.settings.urlMappings && window.settings.urlMappings.length > 0) {
    let mapping = window.settings.urlMappings.find(u => config.url.indexOf(u.prefix) != -1);

    if (mapping) {
      config.url = `${mapping.host}${config.url}`;
    }
  }

  // 超时时间未设置则8分钟
  if (!config.timeout) {
    config.timeout = 1000 * 60 * 8;
  }

  if (config.hideTip != true) {
    message.loading({ content: '正在发起远程调用，请稍候...', key, duration: 0 });
  } else {
    config.hideTip = true;
  }

  if (store.state.oauth.enable) {
    config.headers["Authorization"] = `Bearer ${store.state.oauth.access_token}`;
  }

  return config;
});

/**
* axios响应拦截处理。
*/
axios.interceptors.response.use(response => {
  if (!response.config.hideTip) {
    message.success({ content: '远程调用完成！', key, duration: 1.5 });
  }

  let data = response.data;

  if (response.data.result) {
    data = response.data.result;

    data.success = data.code == 0;
  }

  return data;
}, error => {
  let config = {
    key,
    content: `网络错误:${error}！`,
    duration: 3
  }

  if (error.response) {
    let message = (error.response.data || {}).message;

    message = message || JSON.stringify(error.response.data);

    switch (error.response.status) {
      case 500:
        config.content = `服务器异常:${message}`;

        break;
      case 504:
        config.content = `网络错误:${message}！`;

        break;

      // 401 清除token信息并跳转到登录页面
      case 401:
      case 403:
        config.content = `您没有访问远程接口[${error.request.responseURL}]的权限！`;

        break;
      case 405:
        console.log(error);

        config.content = `${error.response.status} - 远程调用不支持【${error.config.method}】方法！`;

        break;
      default:
        config.content = `${error.response.status} - 远程接口访问出错！`;
    }
  }

  message.error(config);

  return {
    at: getDateTime(),
    success: false,
    status: error.response.status,
    message: config.content
  };
});

export default {
  install
};